//
//  MHZTitleListChainView.swift
//  UNHimalayas
//
//  Created by MaHaoZhe on 2019/11/21.
//  Copyright © 2019 HachiTech. All rights reserved.
//

import UIKit

enum NavigationStyle
{
    case NavigationNormalStyle
    case NavigationSearchStyle
}

let bottomLineWidth = 16
let bottomLineHeight = 3

class MHZTitleListChainView: UIView
{
    var topView :UIView!
    var topTitleCollectionView : UICollectionView!
    var topSearchView : UIView!
    var mainCollectionView : UICollectionView!
    //标签下边的横线
    var bottomLine : UIView!
    
    var titleArr : [String]?
    var topViewHeight : CGFloat!
    //当前选中的标签
    var currentIndex = 0;
    //存储每个标签的长度
    var labelWidthArr = [Float]()
    //是否是点击title更换页面
    var isClickTitle = true
    
    //获取页面数据model
    var recommendPageData : [String]?{
        didSet{
            guard let model = recommendPageData else { return }
            self.titleArr = model
            
            self.labelWidthArr.removeAll()
            
            for titleStr in self.titleArr! {
                let titleWidth = Int((titleStr as NSString).boundingRect(with: CGSize(width: 1000, height: 44), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)], context: nil).size.width) + 20
                self.labelWidthArr.append(Float(titleWidth))
            }
            self.bottomLine.frame = CGRect.init(x: Int(self.getCurrentBottomLineX()), y: 44-bottomLineHeight, width: bottomLineWidth, height: bottomLineHeight)
            self.bottomLine.layer.cornerRadius = CGFloat(bottomLineHeight)/2.0
        }
    }

    convenience init(navigationType:NavigationStyle)
    {
        self.init()
        self.setupSubViews(type: navigationType)
    }
    
    

    func setupSubViews(type:NavigationStyle)
    {
        self.topView = UIView.init()
        self.addSubview(self.topView)
        self.topView.backgroundColor = UIColor.init(hex: 0, alpha: 0);
        if type == NavigationStyle.NavigationSearchStyle
        {
            self.topViewHeight = TOPBARHEIGHT+44
        }
        else
        {
            self.topViewHeight = TOPBARHEIGHT
        }
        self.topView.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(self)
            make.height.equalTo(self.topViewHeight)
        }
        
        //上部title 列表
        let titleLayout = UICollectionViewFlowLayout.init()
        titleLayout.minimumLineSpacing = 0
        titleLayout.minimumInteritemSpacing = 0
        titleLayout.scrollDirection = .horizontal
        titleLayout.collectionView?.isPagingEnabled = true
        titleLayout.collectionView?.bounces = false
        
        self.topTitleCollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: titleLayout)
        self.topTitleCollectionView.delegate = self
        self.topTitleCollectionView.dataSource = self
        self.topTitleCollectionView.register(MHZTitleListChainTitleCell.self, forCellWithReuseIdentifier: "TitleListChainTitleItem")
        self.topTitleCollectionView.backgroundColor = UIColor.init(hex: 0, alpha: 0);
        self.topTitleCollectionView.showsHorizontalScrollIndicator = false
        self.topTitleCollectionView.bounces = false
        self.topView.addSubview(self.topTitleCollectionView)
        
        self.topTitleCollectionView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.top.equalTo(self.topView).offset(UIApplication.shared.statusBarFrame.height)
            make.height.equalTo(44)
        }
        
        self.bottomLine = UIView.init()
        self.bottomLine.backgroundColor = UIColor.red
        self.topTitleCollectionView.addSubview(self.bottomLine)
        
        //中间搜索
        if type == NavigationStyle.NavigationSearchStyle
        {
            self.topSearchView = UIView.init()
            self.topSearchView.backgroundColor = UIColor.init(hex: 0, alpha: 0);
            self.topView.addSubview(self.topSearchView)
            
            self.topSearchView.snp.makeConstraints { (make) in
                make.left.right.equalTo(self.topView)
                make.top.equalTo(self.topTitleCollectionView.snp.bottom)
                make.height.equalTo(44)
            }
        }
        
        //下部控制器列表
        let mainLayout = UICollectionViewFlowLayout.init()
        mainLayout.minimumLineSpacing = 0
        mainLayout.minimumInteritemSpacing = 0
        mainLayout.scrollDirection = .horizontal
        mainLayout.collectionView?.isPagingEnabled = true
        mainLayout.collectionView?.bounces = false
        
        self.mainCollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: mainLayout)
        self.mainCollectionView.backgroundColor = UIColor.white
        self.mainCollectionView.delegate = self
        self.mainCollectionView.dataSource = self
        self.mainCollectionView.register(MHZTitleListChainMainCell.self, forCellWithReuseIdentifier: "TitleListChainMainItem")
//        self.mainCollectionView.bounces = false
        self.mainCollectionView.isPagingEnabled = true
        self.addSubview(mainCollectionView)
        
        self.mainCollectionView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(self)
            make.top.equalTo(self.topView.snp.bottom)
        }
    }
}


//MARK: - 代理方法
extension MHZTitleListChainView:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == self.topTitleCollectionView
        {
            return self.titleArr!.count
        }
        else
        {
            return self.titleArr!.count
        }
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.topTitleCollectionView {
            let item = collectionView.dequeueReusableCell(withReuseIdentifier: "TitleListChainTitleItem", for: indexPath) as! MHZTitleListChainTitleCell
            
            item.titleStr = self.titleArr![indexPath.item]
            
            return item
        }
        else
        {
            let item = collectionView.dequeueReusableCell(withReuseIdentifier: "TitleListChainMainItem", for: indexPath) as! MHZTitleListChainMainCell
            
            return item
        }
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == self.topTitleCollectionView {
            
            let labelWidth = self.labelWidthArr[indexPath.item]
            
            return CGSize.init(width: Int(labelWidth) , height: 44)
        }
        else
        {
            return CGSize.init(width: self.width, height: self.height - self.topViewHeight)
        }
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == topTitleCollectionView {
            isClickTitle = true
            self.mainCollectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.init(), animated: false)
            self.currentIndex = indexPath.item
                        
            //更新标签下划线的位置
            UIView.animate(withDuration: 0.35) {
                self.bottomLine.frame = CGRect.init(x: Int(self.getCurrentBottomLineX()), y: 44-bottomLineHeight, width: bottomLineWidth, height: bottomLineHeight)
            }
            self.bottomLine.layer.cornerRadius = CGFloat(bottomLineHeight)/2.0
            
            //更新标签的位置
            self.updateBottomLineOffsetX()
            
        }
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //是否是点击title更换页面
        if isClickTitle {
            isClickTitle = false
            return
        }
        
        //如果是下部分View滑动 对标题列表做动画操作
        if scrollView == self.mainCollectionView {
            //当前页面下标，单页面偏移量比例
            let ind = CGFloat(scrollView.contentOffset.x/self.width)
            let ratioStr = String(format: "%.2f", (scrollView.contentOffset.x - CGFloat(Int(ind)*Int(self.width)))/self.width)
            
            //计算当前滑动到的下标
            var index = 0
            if scrollView.contentOffset.x < self.width {
                index = 0
            }else{
                index = Int(scrollView.contentOffset.x/self.width)
            }
            
            self.currentIndex = index
            
            let doubleStr = ratioStr as NSString
            
            //更新标签下划线位置
            //判断是左滑还是右滑
            let translatedPoint = scrollView.panGestureRecognizer.translation(in: scrollView)
            
            if translatedPoint.x < 0 {
                // 右滑
                var offset = 0.00
                // 如果下标是最后一个，则用当前下标宽度和后一个下标文本宽度计算偏移量
                if index < self.titleArr!.count-1 {
                    offset = Double(self.labelWidthArr[index] + self.labelWidthArr[index+1])/2*Double(CGFloat(doubleStr.doubleValue))
                }
                if offset == 0 {//换页完成
                    UIView.animate(withDuration: 0.05) {
                        self.bottomLine.frame = CGRect.init(x: Int(self.getCurrentBottomLineX(currentIndex: index, scale: CGFloat(0))), y: 44-bottomLineHeight, width: Int(CGFloat(bottomLineWidth) + CGFloat(offset)), height: bottomLineHeight)
                    }
                }else{
                    //滑栋的过程中
                    self.bottomLine.frame = CGRect.init(x: Int(self.getCurrentBottomLineX(currentIndex: index, scale: CGFloat(0))), y: 44-bottomLineHeight, width: Int(CGFloat(bottomLineWidth) + CGFloat(offset)), height: bottomLineHeight)
                    
                }
                self.bottomLine.layer.cornerRadius = CGFloat(bottomLineHeight)/2.0
                
            }
            
            if translatedPoint.x > 0 && scrollView.contentOffset.x > 0{
                // 左滑
                var offset = 0.00
                
                offset = Double(self.labelWidthArr[index] + self.labelWidthArr[index+1])/2*Double(CGFloat(1 - doubleStr.doubleValue))
                self.bottomLine.frame = CGRect.init(x: Int(self.getCurrentBottomLineX(currentIndex: index, scale: CGFloat(doubleStr.doubleValue))), y: 44-bottomLineHeight, width: Int(CGFloat(bottomLineWidth) + CGFloat(offset)), height: bottomLineHeight)
                
                self.bottomLine.layer.cornerRadius = CGFloat(bottomLineHeight)/2.0
                
                
            }
        }
    }
    
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView == self.mainCollectionView {
            self.currentIndex = Int(scrollView.contentOffset.x/self.width)
            
            self.updateBottomLineOffsetX()
            
//            UIView.animate(withDuration: 0.05) {
                self.bottomLine.frame = CGRect.init(x: Int(self.getCurrentBottomLineX(currentIndex: self.currentIndex, scale: 0.0)), y: 44-bottomLineHeight, width: bottomLineWidth, height: bottomLineHeight)
//            }
            self.bottomLine.layer.cornerRadius = CGFloat(bottomLineHeight)/2.0
            self.isClickTitle = false
        }
    }
}


//MARK: - 工具方法
extension MHZTitleListChainView {
    //获取当前标签下划线的位置
    func getCurrentBottomLineX()->Double{
        var currentX = 0.0
        
        for index in 0..<self.currentIndex {
            currentX += Double(self.labelWidthArr[index])
        }
        
        currentX += (Double(self.labelWidthArr[self.currentIndex])/2 - Double(bottomLineWidth/2))
        
        return currentX
    }
    
    
    
    
    
    //更新标签的位置
    func updateBottomLineOffsetX() {
        if self.getCurrentBottomLineX() >= Double(self.width/2)
        {
            //防止前半截或后半截移动到中央
            if self.getCurrentBottomLineX() >= (Double(self.topTitleCollectionView.contentSize.width) - Double(self.width/2)) {
                self.topTitleCollectionView.setContentOffset(CGPoint.init(x: self.topTitleCollectionView.contentSize.width - self.width, y: 0), animated: true)
            }else{
                self.topTitleCollectionView.setContentOffset(CGPoint.init(x: CGFloat(self.getCurrentBottomLineX())-(self.width-CGFloat(bottomLineWidth))/2, y: 0), animated: true)
            }
        }else{
            self.topTitleCollectionView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: true)
        }
    }
    
    
    //滑动式获取实时下标位置
    func getCurrentBottomLineX(currentIndex : Int,scale : CGFloat)->Double{
        var currentX = 0.0
        
        if currentIndex > 0 {
            for index in 0..<currentIndex {
                currentX += Double(self.labelWidthArr[index])
            }
        }
        
        var offsetX = 0.0
        if currentIndex < self.titleArr!.count-1 {
            offsetX = Double(self.labelWidthArr[currentIndex] + self.labelWidthArr[currentIndex+1])/2*Double(scale)
        }
        currentX += (Double(self.labelWidthArr[currentIndex])/2 - Double(bottomLineWidth/2)) + offsetX
        return currentX
    }
    
    //更新标签下划线尾部位置
    func updateBottomLineTailX(currentIndex : Int,scale : CGFloat)->Double{
        var currentX = 0.0
        
        if currentIndex > 0 {
            for index in 0..<currentIndex {
                currentX += Double(self.labelWidthArr[index])
            }
        }
        
        var offsetX = 0.0
        if currentIndex < self.titleArr!.count-1 {
            offsetX = Double(self.labelWidthArr[currentIndex] + self.labelWidthArr[currentIndex+1])/2*Double(scale)
        }
        currentX += (Double(self.labelWidthArr[currentIndex])/2 - Double(bottomLineWidth/2)) + offsetX
        return currentX
    }
}


extension MHZTitleListChainView: CAAnimationDelegate {
    
}
